package chat.keepWind.util;


import java.awt.Color;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JWindow;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

import chat.keepWind.bean.DataPackage;
import chat.keepWind.bean.User;
import chat.keepWind.event.SendCapImg;
import chat.keepWind.event.SendMessage;
import chat.keepWind.ui.ChatUI;
import chat.keepWind.ui.Screenshot;
import io.netty.util.CharsetUtil;


public class ChatUtil {
	
	
	public static Map<String ,Object> dataMap = new HashMap<>(); 
	
	
	@SuppressWarnings("unchecked")
	public static ChatUI openChat(final String toIp,String toNickName){
		final ChatUI chatui;
		final Map<String,ChatUI> chats = (Map<String,ChatUI>)dataMap.get("chats");
		final String myIP = (String)dataMap.get("ip");
		
		if(chats.get(toIp)==null){ 
			chatui = new ChatUI(myIP,toIp,toNickName);
			chatui.getwinFrame();
			chatui.getWin().setVisible(true);
			chatui.getWin().setTitle("与用户(" + toNickName + ")对话中");
			chats.put(toIp, chatui);
			
			chatui.getwinFrame().addWindowListener(new WindowAdapter() {
				public void windowClosing(WindowEvent e) {
					chats.remove(toIp);
				}
			});
			
			/**
			 * 发送 按钮监听，已经带了ctrl+enter发送消息监听
			 */
			chatui.getSendBtn().addActionListener(new ActionListener() {
				
				public void actionPerformed(ActionEvent e) {
					if(chatui.isCapScr()){//是否有截图
						List<DataPackage> imgPkgs = new ArrayList<>();
						SendCapImg sndImg = new SendCapImg();
						//截图
						List<String> srcImgs = (List<String>)ChatUtil.dataMap.get("screenImgs");
						DataPackage imgPkg  = null;
						for(String img:srcImgs){
							imgPkg = new DataPackage();
							imgPkg.setFromIp(myIP);
							imgPkg.setToIp(toIp);
							imgPkg.setMsgType(GlobalConst.TYPE_RCV_CAPIMG);
							imgPkg.setFileName(img+".jpg");
							imgPkg.setSrcPath(GlobalConst.CAP_IMG_PATH+img+".jpg");
							imgPkg.setFileLen(new File(GlobalConst.CAP_IMG_PATH+img+".jpg").length());
							imgPkgs.add(imgPkg);
						}
						sndImg.send(toIp, imgPkgs);
						
						sendText(chatui, toIp);
						chatui.setCapScr(false);//重置截图标志
					}else{
						sendText(chatui, toIp);
					}
				}
				
			});
			/**
			 * ctrl+enter发送消息 监听
			 */
			/*chatui.getInputChatArea().addKeyListener(new KeyAdapter() {
				    private boolean isPressed = false;
	    			public void keyPressed(KeyEvent e) {
	    				if (KeyEvent.VK_CONTROL == e.getKeyCode()) {
	    					isPressed = true;
	    				}
	    				if (e.getKeyCode() == KeyEvent.VK_ENTER && isPressed) {
	    					System.out.println("==================");
	    					sendText(chatui, toIp);
	    				}
	    			}

	    			public void keyReleased(KeyEvent e) {
	    				if (KeyEvent.VK_CONTROL == e.getKeyCode() || KeyEvent.VK_ENTER == e.getKeyCode()) {
	    					isPressed = false;
	    				}
	    			}
	    		});*/
			/**
			 * 关闭按钮监听
			 */
			chatui.getCloseBtn().addActionListener(new ActionListener() {
				
				public void actionPerformed(ActionEvent e) {
					chats.remove(toIp);
					chatui.getWin().dispose();
				}
			});
			/**
			 * 发送文件按钮 监听
			 */
			chatui.getFileBtn().addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					
					JFileChooser chooser = new JFileChooser(".");
					chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
					int status = chooser.showOpenDialog(chatui.getWin().getRootPane());
					File file = chooser.getSelectedFile();
					if (file == null || status == JFileChooser.CANCEL_OPTION) {
						return;
					}
					if (status == JFileChooser.APPROVE_OPTION) {
						String path = file.getPath();
						String fileName = file.getName();
						
						preSendFile(chatui, toIp, path, fileName,file.length());
					}
					
				}
			});
			/**
			 * 表情按钮行为事件监听
			 */
			chatui.getLookBtn().addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					final JWindow jWindow = new JWindow(chatui.getWin());
					jWindow.setLayout(new GridLayout(5, 5, 5, 5));
					jWindow.setAlwaysOnTop(true);
					jWindow.setBounds(300, 100, 350, 210);
					jWindow.setLocationRelativeTo(chatui.getLookBtn());
					int jwX = jWindow.getX()
							+ (jWindow.getWidth() - chatui.getLookBtn().getWidth()) / 2;
					int jwY = jWindow.getY()
							+ (jWindow.getHeight() - chatui.getLookBtn().getHeight()) / 2;
					jWindow.setLocation(jwX, jwY);
					jWindow.setFocusable(true);
					JLabel[] ico = new JLabel[45];
					String fileName = "";
					String desc = "";
					for (int i = 1; i < ico.length; i++) {
						if (i < 10){
							fileName = "/picture/#[0" + i + "].gif";
							desc = "#[0" + i + "]";
						}else if (i >= 10){
							fileName = "/picture/#[" + i + "].gif";
							desc = "#[" + i + "]";
						}
						ico[i] = new JLabel(new ImageIcon(Toolkit
								.getDefaultToolkit().getImage(getClass().getResource(fileName))
										,desc));
						final Icon img1 = ico[i].getIcon();
						
						ico[i].addMouseListener(new MouseAdapter() {
							public void mouseClicked(MouseEvent e) {
								chatui.getInputChatArea().insertIcon(img1);
								jWindow.dispose();
							}
						});
						jWindow.add(ico[i]);
					}
					jWindow.setBackground(SystemColor.text);
					jWindow.setVisible(true);

					jWindow.addFocusListener(new FocusListener() {

						@Override
						public void focusLost(FocusEvent arg0) {
							// TODO Auto-generated method stub
							jWindow.dispose();
						}

						@Override
						public void focusGained(FocusEvent arg0) {
						
						}
					});
				}

			});
			/**
			 * 截图按钮 事件监听
			 */
			chatui.getCapBtn().addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					new Screenshot(chatui);
				}
			});
			/**
			 * 清屏按钮 事件监听
			 */
			chatui.getClearBtn().addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					chatui.getDsiplChatArea().setText("");
					chatui.getDsiplChatArea().removeAll();
				}
			});
		}else{
			chatui = chats.get(toIp);
			chatui.getWin().setVisible(true);
		}
		
		return chatui;
	}
	/**
	 * 发送数据包
	 */
	public static void sendDataPackage(String toIp,String type,String content){
		String myIP = (String)dataMap.get("ip");
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		DataPackage data = new DataPackage();
		data.setFromIp(myIP);
		data.setToIp(toIp);
		data.setMsgType(type);
		data.setMsgContent(content.getBytes(CharsetUtil.UTF_8));
		data.setSendTime(sdf.format(new Date()));
		
		SendMessage snd = new SendMessage();
		snd.send(toIp, data);
	}
	/**
	 * 发送 文本消息
	 */
	public static void sendText(ChatUI chatui,String toIp){
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String head = "\n"+"我（"+sdf.format(new Date())+"）："+"\n";
		
		String msg = showTalk(chatui, head,"");
		
		
		/*JButton but = new JButton();
		
		but.setIcon(new ImageIcon(Toolkit
				.getDefaultToolkit().getImage(Thread.currentThread().getClass().getResource("/picture/rcvBtn1.png"))));
	
		but.setBorderPainted(false);
		chatui.getDsiplChatArea().insertComponent(but);*/
		
		//发送消息
		if(!"".equals(msg)){
			sendDataPackage(toIp,GlobalConst.TYPE_TXT,msg);
		}
	}
	/**
	 * 准备传送文件
	 */
	public static void preSendFile(ChatUI chatui,String toIp,String srcPath,String fileName,long len){
		Document doc = chatui.getDsiplChatArea().getStyledDocument();
		
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		SimpleAttributeSet headAttr = new SimpleAttributeSet();
		StyleConstants.setBold(headAttr, true);
		StyleConstants.setForeground(headAttr, new Color(88, 185, 242));
		
		String head = "\n"+"我（"+sdf.format(new Date())+"）："+"\n";
		String text = "发送了一个文件（"+fileName+"），准备被接收";
		
		try {
			doc.insertString(doc.getLength(), head,  headAttr);
			doc.insertString(doc.getLength(), text,  new SimpleAttributeSet());
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
		chatui.getDsiplChatArea().setSelectionStart(doc.getLength());
		chatui.getDsiplChatArea().setSelectionEnd(doc.getLength());
		//发送消息
		
		String myIP = (String)dataMap.get("ip");
		
		
		DataPackage data = new DataPackage();
		data.setFromIp(myIP);
		data.setToIp(toIp);
		data.setMsgType(GlobalConst.TYPE_FILE);
		data.setMsgContent("".getBytes(CharsetUtil.UTF_8));
		data.setSendTime(sdf.format(new Date()));
		data.setSrcPath(srcPath);
		data.setFileName(fileName);
		data.setFileLen(len);
		
		SendMessage snd = new SendMessage();
		snd.send(toIp, data);
	}
	
	/**
	 * 对话显示在 界面上
	 * @param body 为接受到的文本消息 ;为null或空字符，则为界面的输入
	 */
	@SuppressWarnings("unchecked")
	public static String showTalk(ChatUI chatui,String head,String body){
		
		
		ArrayList<String> picList = new ArrayList<String>();
		StyledDocument doc = chatui.getDsiplChatArea().getStyledDocument();
		
		SimpleAttributeSet headAttr = new SimpleAttributeSet();
		StyleConstants.setBold(headAttr, true);
		StyleConstants.setForeground(headAttr, new Color(88, 185, 242));
		if(body!=null && !"".equals(body)){
			StyleConstants.setForeground(headAttr, new Color(66, 141, 94));
		}
		SimpleAttributeSet attr = new SimpleAttributeSet();
		
		try {
			doc.insertString(doc.getLength(), head,  headAttr);
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
		
		String talkContent = "";
		if(body!=null && !"".equals(body)){
			talkContent = body;
		}else{
			StyledDocument inputDoc = chatui.getInputChatArea().getStyledDocument();
			
			Element root = inputDoc.getRootElements()[0];

			for(int j=0;j<root.getElementCount();j++){
				//System.out.println("j=="+j);
				Element ele = root.getElement(j);
				
				int eleCnt = ele.getElementCount();
				for(int i = 0; i<eleCnt;i++){
					//System.out.println("i=="+i);
					Icon icon = StyleConstants.getIcon(ele.getElement(i).getAttributes());
					if (icon != null) {
						//System.out.println("============"+icon.toString());
						picList.add(icon.toString());
					}
				}
			}
			
			int k = 0;
			int len =  chatui.getInputChatArea().getText().length();
			//截图
			List<String> srcImgs = (List<String>)ChatUtil.dataMap.get("screenImgs");
			for (int i = 0; i < len; i++) {
				if (inputDoc.getCharacterElement(i).getName()
						.equals("icon")) {
					String imgName = picList.get(k);
					if(imgName.length()<6){
						//表情包转换
						for (int j = 1; j < 46; j++) {
							if (imgName.equals("#[0" + j + "]")) {
								talkContent += "#[0" + j+"]";
								
								break;
							}else if (imgName.equals("#[" + j + "]")) {
								talkContent += "#[" + j+"]";
								break;
							}
						}
					}else{
						//截图 转换
						if(srcImgs!=null && srcImgs.size()>0){
							for(int j=0;j<srcImgs.size();j++){
								String tmp = srcImgs.get(j);
								if(imgName.equals(tmp)){
									talkContent += tmp;
									break;
								}
							}
						}
					}
					k++;
				} else {
					try {
						String s = inputDoc.getText(i, 1);//文本
						if(i==len-1 && s.equals("\n")){
							//System.out.println("继续");
							continue;
						}
						talkContent += s;
					} catch (BadLocationException e1) {
						talkContent = talkContent.substring(0, talkContent.length()-1);
						System.out.println("出错！");
						//e1.printStackTrace();
						break;
					}
				}
			}
			ChatUtil.dataMap.remove("screenImgs");//移除截图集
		}
		
		
		int length = talkContent.length();
		
		int count = 0;// 初始字符的位置
		String path = "/picture/";
		
		
		Boolean flag = false;
		if(talkContent.contains("#[")){
			flag = true;
		}
		//如果有表情或截图
		if(flag){
			for (int i = 0; i < talkContent.length(); i++) {
				if (talkContent.charAt(i) == '#' && talkContent.charAt(i+1) == '[') {
					String str = null;
					str = talkContent.substring(count, i); // 得到图片前的文字

					try {
						if (str != null){
							doc.insertString(doc.getLength(), str, attr);// 添加表情前的文字
						}
					} catch (Exception e2) {
						e2.printStackTrace();
					}
					String icName;
					icName = talkContent.substring(i, i + 5);// 得到表情的名字
					//表情为5个字符,截图为16字符
					if(icName.charAt(icName.length()-1)==']'){
						
						Icon ic = new ImageIcon(Toolkit
								.getDefaultToolkit().getImage(Thread.class.getResource(path + icName + ".gif")));
						chatui.getDsiplChatArea().setCaretPosition(doc.getLength());
						chatui.getDsiplChatArea().insertIcon(ic); // 加入表情
						count = i + 5;// 将字符起始位置跳到表情后第一位置
					}else{
						icName = talkContent.substring(i, i + 16);// 得到截图的名字
					
						Icon ic = new ImageIcon(GlobalConst.CAP_IMG_PATH +icName + ".jpg");
						chatui.getDsiplChatArea().setCaretPosition(doc.getLength());
						chatui.getDsiplChatArea().insertIcon(ic); // 加入截图
						count = i + 16;// 将字符起始位置跳到表情后第一位置
					}
					
				}
			}
		}
		
		//纯文本 或 最后一段文本
		if (count < talkContent.length()) {
			String theLast = null;
			theLast = talkContent.substring(count, length);
			try {
				doc.insertString(doc.getLength(), theLast, attr);
			} catch (Exception e3) {
				e3.printStackTrace();
			}
		}
		chatui.getDsiplChatArea().setCaretPosition(doc.getLength());
		
		if(body==null || "".equals(body)){
			chatui.getInputChatArea().setText("");// 清空输入框
		}
		
		return talkContent;
	}
	
	/*public static String getNickName(String ip){
		Config config = (Config)dataMap.get("config");
		Map<String,User> userMap = config.getUserMap();
		User u = userMap.get(ip);
		if(u!=null){
			return u.getNickName();
		}
		return null;
	}*/
	/**
	 * 获取备注 昵称
	 * @param ip
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String getNickName(String ip){
		List<User> onlineUsers = (List<User>)ChatUtil.dataMap.get("onlineUsers");
		for(User user:onlineUsers){
			if(ip.equals(user.getIp())){
				return user.getNickName();
			}
		}
		return "";
	}
	/**
	 * 在线用户集合中是否存在该IP
	 * @param users
	 * @param ip
	 * @return
	 */
	 public static User isExsitsIp(List<User> users,String ip){
    	for(User u : users){
    		if(ip.equals(u.getIp())){
    			return u;
    		}
    	}
    	return null;
	 }
} 
